package cn.edu.scau.cmi.chensicheng.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.edu.scau.cmi.chensicheng.domain.Teacher;

public class TeacherDAO extends BaseHibernateDAO {
	public static final String NAME = "name";

	public void save(Teacher teacher) {
		Session session = getSession();
		Transaction transaction = session.beginTransaction();
		session.save(teacher);
		transaction.commit();
		session.close();
	}

	public void delete(Teacher teacher) {
		Session session = getSession();
		Transaction transaction = session.beginTransaction();
		session.delete(teacher);
		transaction.commit();
		session.close();
	}

	public void update(Teacher teacher) {
		Session session = getSession();
		Transaction transaction = session.beginTransaction();
		session.update(teacher);
		transaction.commit();
		session.close();
	}

	public Teacher findById(Long id) {
		Session session = getSession();
		Teacher teacher = (Teacher) session.get("cn.edu.scau.cmi.chensicheng.domain.Teacher", id);
		session.close();
		return teacher;
	}

	public List<Teacher> findByProperty(String propertyName, Object value) {
		Session session = getSession();
		String queryString = "select * from teacher where " + propertyName + " = ?";
		Query queryObject = session.createSQLQuery(queryString).addEntity(Teacher.class);
		queryObject.setParameter(0, value);
		List<Teacher> list = queryObject.list();
		session.close();
		return list;
	}

	public Teacher findByName(String name) {
		List<Teacher> list = findByProperty(NAME, name);
		if (list.size() > 0) {
			return (Teacher) list.get(0);
		}
		return null;
	}

	public List<Teacher> findAll() {
		Session session = getSession();
		String queryString = "select * from teacher";
//		sql语句查询最后要调用addEntity(要转换成的对象.class) 转换成要转成的对象 否则报映射异常
		Query queryObject = session.createSQLQuery(queryString).addEntity(Teacher.class);
		List<Teacher> list = queryObject.list();
		session.close();
		return list;
	}
}
